﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace PMRC.API.Helper
{
    public class TokenHelpr
    {
        private readonly IConfiguration _configuration;

        public TokenHelpr(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public async Task<string> GenerateTokenAsync()
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(_configuration["JwtConfig:SecretKey"]);
            var issuer = _configuration["JwtConfig:Issuer"];
            var audience = _configuration["JwtConfig:Audience"];
            var expirationInHours = int.Parse(_configuration["JwtConfig:ExpirationInHours"]);

            //var roles = new List<SysRole>();

            //var roleNames = roles.Select(x => x.Name).ToList();

            var claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.NameIdentifier,""),
                new Claim(ClaimTypes.Name, "")
            });
            //foreach (var roleName in roleNames)
            //{
            //    claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, roleName));
            //}
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claimsIdentity,
                Expires = DateTime.Now.AddHours(expirationInHours),
                Issuer = issuer,
                Audience = audience,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
    }
}
